package com.example.java.service;

import com.example.java.pojo.User;
import com.example.java.pojo.UserAddress;
import com.example.java.pojo.dto.UserAddressDto;
import com.example.java.repository.UserAddressRepository;
import com.example.java.repository.UserRepository;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserAddressService implements IUserAddressService{

    @Autowired
    UserAddressRepository userAddressRepository;

    @Autowired
    UserRepository userRepository;

    //添加一个地址
    @Override
    public UserAddress addAddress(UserAddressDto userAddress) {

        //验证是否传入用户id,注意是用户id，而不是地址的id
        if(userAddress.getUser_id() == null)
        {
            throw new IllegalArgumentException("请传入用户id");
        }

        //先检查地址所带的用户id是否存在,存在就返回这个用户的信息
        Integer useraddressid = userAddress.getUser_id();
        User user = userRepository.findById(useraddressid).orElseThrow(()->{
           throw  new IllegalArgumentException("用户不存在，ID:"+useraddressid);
        });

        //创建一个useraddressPojo实体
        UserAddress userAddressPojo = new UserAddress();
        userAddressPojo.setNicknameAddress(userAddress.getNickname_address());
        userAddressPojo.setPhoneAddress(userAddress.getPhone_address());
        userAddressPojo.setProvince(userAddress.getProvince());
        userAddressPojo.setCity(userAddress.getCity());
        userAddressPojo.setDistrict(userAddress.getDistrict());
        userAddressPojo.setAddressDetail(userAddress.getAddress_detail());
        userAddressPojo.setDefault(userAddress.isIs_default());
        //将用户id存在地址的表中，将两者关联起来
        userAddressPojo.setUser(user);

        // 处理默认地址逻辑
        handleDefaultAddress(user, userAddressPojo, userAddress.isIs_default());

        //将地址对象传入用户的地址列表里面
        user.addAddress(userAddressPojo);

        return userAddressRepository.save(userAddressPojo);
    }

    /**
     * 处理默认地址逻辑，确保用户只有一个默认地址
     *
     * @param user 用户对象
     * @param newAddress 新地址
     * @param setAsDefault 是否设置为默认地址
     */
    private void handleDefaultAddress(User user, UserAddress newAddress, boolean setAsDefault) {
        List<UserAddress> existingAddresses = user.getAddresses();

        // 情况1: 用户没有地址，新地址自动设为默认
        if (existingAddresses.isEmpty()) {
            newAddress.setDefault(true);
            return;
        }

        // 情况2: 新地址被设为默认
        if (setAsDefault) {
            // 取消所有现有默认地址
            existingAddresses.stream()
                    .filter(UserAddress::isDefault)
                    .forEach(addr -> {
                        addr.setDefault(false);
                        userAddressRepository.save(addr); // 立即更新
                    });
            newAddress.setDefault(true);
        }
        // 情况3: 新地址不设为默认
        else {
            newAddress.setDefault(false);
        }
    }

    //根据addressid来删除一个地址
    @Override
    public void deleteUserAddress(Integer id) {
        //先查询这个地址id是否存在
        UserAddress address = userAddressRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("未找到对应地址id"+id));
        //先去删除其对应用户下的地址
        User user = address.getUser();
        user.removeAddress(address);
        // 如果删除的是默认地址，设置新的默认地址
        if (address.isDefault() && !user.getAddresses().isEmpty()) {
            user.getAddresses().get(0).setDefault(true);
        }

        userAddressRepository.deleteById(id);
    }
}
